<?php

namespace App\Transformers;

use App\Models\Category;
use League\Fractal\TransformerAbstract;

class CategoryTransformer extends TransformerAbstract
{
    public function transform(Category $category)
    {
        $parent_id = $category->parent ? $this->formatParent($category->parent) : null;
        $parent = $parent_id ? array_filter(array_flatten($parent_id)) : [0];
        sort($parent);

        return [
            'id' => $category->id,
            'parent_id' => $parent,
            'title' => $category->title,
            'description' => $category->description,
            'sort' => $category->sort,
            'children' => $category->children ? $this->formatChildren($category->children) : null,
        ];
    }

    /**
     * @author Vance
     *
     * @param $res
     * @return array|null
     */
    protected function formatChildren($res)
    {
        if (count($res) == 0) {
            return null;
        }

        $data = [];
        foreach ($res as $item) {
            $parent_id = $item->parent ? $this->formatParent($item->parent) : null;
            $parent = $parent_id ? array_filter(array_flatten($parent_id)) : null;
            sort($parent);

            $data[] = [
                'id' => $item->id,
                'parent_id' => $parent,
                'title' => $item->title,
                'description' => $item->description,
                'sort' => $item->sort,
                'children' => $item->children ? $this->formatChildren($item->children) : null,
            ];
        }

        return $data;
    }

    /**
     * @author Vance
     *
     * @param $res
     * @return array|null
     */
    protected function formatParent($res)
    {
        if (count($res) == 0) {
            return null;
        }

        $data = [
            'id' => $res->id,
            'parent' => $res->parent ? $this->formatParent($res->parent) : null,
        ];

        return $data;
    }
}